package com.person.jc.web.service;

import java.util.List;
import java.util.Map;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.person.jc.common.Constants;
import com.person.jc.entity.TsUser;
import com.person.jc.service.service.BsOrderService;
import com.person.jc.service.service.BsRepairConfirmService;
import com.person.jc.service.test.inspect.BsRepairRegLogService;
import com.person.jc.utils.Servlets;
import com.person.jc.utils.SessionKit;

//TODO 维修确认
public class BsRepairConfirmController extends Controller {
	
	public void init(){
		setAttr("menuId", getPara("menuId"));
		render("main.jsp");
	}

	public void list(){
		Map<String, Object> map = Servlets.getParametersStartingWith(getRequest(), "p_");
		TsUser tsUser = (TsUser)SessionKit.get().getAttribute(Constants.LOGIN_USER);
		map.put("serviceUser", tsUser.getUserId());
		map.put("orderType","2");
		List<Record> list = BsRepairConfirmService.me.getList(map);
		setAttr("list", list);
		render("list.jsp");
	}
	
	public void edit(){
		Map<String, Object> map = Servlets.getParametersStartingWith(getRequest(), "p_");
		map.put("orderType","2");
		map.put("flowId", Constants.FLOW_WX_JCRW);
		Record obj = BsOrderService.me.getOrderInfo(String.valueOf(map.get("orderId")));
		List<Record> details = BsRepairRegLogService.me.getViewList(map);
		setAttr("obj", obj);
		setAttr("details", details);
		setAttr("view", getPara("view"));
		render("edit.jsp");
	}
	
	@Before(Tx.class)
	public void save(){
		TsUser tsUser = (TsUser)SessionKit.get().getAttribute(Constants.LOGIN_USER);
		String[] logId = getParaValues("logId");
		String[] confirmStatus = getParaValues("confirmStatus");
		BsRepairConfirmService.me.delete(logId);
		String logIds = "";
		if(logId.length != 0){
			Object[][] params = new Object[logId.length][3];
			for (int i = 0; i < logId.length; i++) {
				params[i][0] = (logId != null && logId.length >= i ) ? logId[i] : "0";
				params[i][1] = ( confirmStatus != null && confirmStatus.length >= i )  ? confirmStatus[i] : "-1";
				params[i][2] = tsUser.getUserId();
				logIds += (logId != null && logId.length >= i ) ? logId[i]+"," : "";
			}
			BsRepairConfirmService.me.save(logIds, params, logId.length);
			
			//不维修的退还配件
			logIds = "";
			for (Object[] obj : params) {
				String status = String.valueOf(obj[1]);
				if("0".equals(status)){
					if(!"".equals(logIds))
						logIds += ",";
					logIds += obj[0]+"";
				}
			}
			if(!"".equals(logIds)){
				BsRepairConfirmService.me.resetParts(logIds);
			}
		}
		
		/*
		 * 判断订单是否已确认完，检查完的更新订单FLOWID;
		 */
		BsRepairConfirmService.me.changeOrderFlow(logId);
		renderText("success");
	}
}
